package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Permission;
import cn.wolfcode.rbac.mapper.PermissionMapper;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IPermissionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper mapper;
    @Autowired
    private ApplicationContext ctx;
    public void saveOrUpdate(Permission u) {
        if(u.getId()==null){
            mapper.insert(u);
        }else{
            mapper.updateByPrimaryKey(u);
        }
    }


    public void delete(Long id) {
        mapper.deleteByPrimaryKey(id);
        mapper.deleteFromRolePermission(id);
    }


    public PageInfo query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Permission> result = mapper.queryForList(qo);
        return new PageInfo(result);
    }


    public Permission selectOne(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    public List<Permission> listAll() {
        return mapper.selectAll();
    }

    public void reload() {
        List<String> expressions = mapper.selectAllExpression();
        Map<String, Object> beans = ctx.getBeansWithAnnotation(Controller.class);
        Collection<Object> controllers = beans.values();
        for(Object object : controllers){
            Method[] methods  = object.getClass().getSuperclass().getDeclaredMethods();
            for (Method m:methods){
                RequiresPermissions annotation = m.getAnnotation(RequiresPermissions.class);
                if(annotation!=null){
                    String name = annotation.value()[0];
                    String expression = annotation.value()[1];
                    if(!expressions.contains(expression)){
                        mapper.insert(new Permission(null,name,expression));
                    }
                }
            }
        }
    }

    public List<String> selectExpressionByEMPId(Long id) {
        List<String> expression = mapper.selectExpressionByEMPId(id);
        return expression;
    }


}
